package com.min.netty.broadcater;

import com.min.netty.codec.LogEventEncoder;
import com.min.netty.model.LogEvent;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * CREATE BY 2018/9/10
 *
 * @author sirmin
 */
public class LogEventBroadcaster {
    private EventLoopGroup eventLoopGroup;
    private Bootstrap bootstrap;
    private File file;
    private boolean stop;
    private BlockingQueue<String> queue = new LinkedBlockingQueue<>();

    public LogEventBroadcaster(InetSocketAddress inetSocketAddress, File file) {
        this.file = file;
        this.eventLoopGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap().group(eventLoopGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new LogEventEncoder(inetSocketAddress));
    }

    public void stop() throws InterruptedException {
        if (eventLoopGroup != null) {
            eventLoopGroup.shutdownGracefully();
        }
        stop = true;
        queue.take();
    }

    public void run() throws Exception {
        final Channel channel = bootstrap.bind(0).sync().channel();
        long pointer = 0;
        while (!stop) {
            final long length = file.length();
            if (length == pointer) {
            } else if (length < pointer) {
                pointer = length;
            } else {
                final RandomAccessFile r = new RandomAccessFile(file, "r");
                r.seek(pointer);
                String line;
                while ((line = r.readLine()) != null) {
                    channel.writeAndFlush(new LogEvent(file.getAbsolutePath(),
                            new String(line.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.UTF_8) + "\n"));
                }
                pointer = r.getFilePointer();
            }
            Thread.sleep(1000);
        }
        channel.close().sync();
        System.out.println("aaaa");
        queue.put("");

    }
}
